import 'package:flutter/material.dart';

class RatingStars extends StatefulWidget {
  final double rating;
  final ValueChanged<double> onRatingChanged;
  final double starSize;
  final Color selectedColor;
  final Color unselectedColor;
  final double halfStarFraction; // 支持半星的分数（0-1）
  final bool isReadOnly; // 只读模式
  final double precision; // 评分精度（0.5或1.0）
  final Duration animationDuration; // 动画时长
  final Curve animationCurve; // 动画曲线

  const RatingStars({
    super.key,
    this.rating = 0,
    required this.onRatingChanged,
    this.starSize = 24,
    this.selectedColor = Colors.amber,
    this.unselectedColor = Colors.grey,
    this.halfStarFraction = 0,
    this.isReadOnly = false,
    this.precision = 1.0, // 默认精度为1.0（整星）
    this.animationDuration = const Duration(milliseconds: 200),
    this.animationCurve = Curves.easeOut,
  });

  @override
  State<RatingStars> createState() => _RatingStarsState();
}

class _RatingStarsState extends State<RatingStars> with SingleTickerProviderStateMixin {
  late AnimationController _animationController;
  late Animation<double> _scaleAnimation;

  @override
  Widget build(BuildContext context) {
    return Row(
      mainAxisSize: MainAxisSize.min,
      children: List.generate(5, (index) {
        final isFullStar = index < widget.rating.floor();
        final isHalfStar = index == widget.rating.floor() && widget.halfStarFraction > 0 && widget.rating % 1 >= 0.5;
        final isEmptyStar = index >= widget.rating.ceil();

        final isSelected = isFullStar || isHalfStar;

        return GestureDetector(
          onTap: widget.isReadOnly ? null : () => _handleStarTap(index + 1),
          child: ScaleTransition(
            scale: _scaleAnimation,
            child: Container(
              width: widget.starSize,
              height: widget.starSize,
              margin: const EdgeInsets.only(right: 4),
              child:
                  isFullStar
                      ? _buildFullStar()
                      : isHalfStar
                      ? _buildHalfStar()
                      : _buildEmptyStar(),
            ),
          ),
        );
      }),
    );
  }

  @override
  void dispose() {
    _animationController.dispose();
    super.dispose();
  }

  @override
  void initState() {
    super.initState();
    _animationController = AnimationController(vsync: this, duration: widget.animationDuration);
    _scaleAnimation = Tween<double>(
      begin: 1.0,
      end: 1.2,
    ).animate(CurvedAnimation(parent: _animationController, curve: widget.animationCurve));
  }

  Widget _buildEmptyStar() {
    return Icon(Icons.star_border, size: widget.starSize, color: widget.unselectedColor);
  }

  Widget _buildFullStar() {
    return Icon(Icons.star, size: widget.starSize, color: widget.selectedColor);
  }

  Widget _buildHalfStar() {
    return Icon(Icons.star_half, size: widget.starSize, color: widget.selectedColor);
  }

  void _handleStarTap(int newRating) {
    // 重置动画
    _animationController.reset();
    _animationController.forward().then((_) => _animationController.reverse());

    // 应用评分精度
    final adjustedRating = (newRating / widget.precision).floor() * widget.precision;

    // 检查是否点击了当前选中的最后一颗星
    if (adjustedRating == widget.rating) {
      // 如果是，取消选择（设置为0）
      widget.onRatingChanged(0);
    } else {
      // 否则，设置新的评分
      widget.onRatingChanged(adjustedRating);
    }
  }
}
